package com.jkgj.skykingkong.tms.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.jkgj.skykingkong.tms.infrastructure.security.SecurityUserProvider;
import io.ebean.EbeanServer;
import io.ebean.EbeanServerFactory;
import io.ebean.config.ServerConfig;
import io.ebean.spring.txn.SpringJdbcTransactionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.ebean.repository.config.EnableEbeanRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @author Xuegui Yuan
 */
@Configuration
@EnableEbeanRepositories("com.jkgj.skykingkong.tms.domain.model")
@EnableTransactionManagement
public class EbeanConfiguration {
  @SuppressWarnings("SpringJavaAutowiringInspection")
  @Bean
  @Primary
  public ServerConfig defaultEbeanServerConfig() {
    ServerConfig config = new ServerConfig();

    config.setDataSource(dataSource());
    config.setExternalTransactionManager(new SpringJdbcTransactionManager());

    config.loadFromProperties();
    config.setDefaultServer(true);
    config.setRegister(true);
    config.setAutoCommitMode(false);
    config.setExpressionNativeIlike(true);
    config.setCurrentUserProvider(new SecurityUserProvider());

    return config;
  }

  @Bean
  public DataSource dataSource() {
    return DruidDataSourceBuilder.create().build();
  }

  @Bean
  @Primary
  public EbeanServer defaultEbeanServer(ServerConfig defaultEbeanServerConfig) {
    return EbeanServerFactory.create(defaultEbeanServerConfig);
  }
}
